package name.zeno.qrcode.library

import android.app.AlertDialog
import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import kotlinx.android.synthetic.main.fragment_qrcode_reader.*
import kotlinx.android.synthetic.main.fragment_qrcode_reader.view.*
import name.zeno.ktrxpermission.ZPermission
import name.zeno.ktrxpermission.rxPermissions

/**
 * - [observable] 监听二维码结果, 仅一次
 * - [fromAlbum] 从相册图片识别二维码
 *
 * @author 陈治谋 (513500085@qq.com)
 * @since 2017/11/30
 */
class QRCodeReaderFragment : Fragment() {
  private val subject = BehaviorSubject.create<QRCode>()
  private val helper by lazy { PhotoCaptureHelper(this) }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.fragment_qrcode_reader, container, false)
  }

  override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val qrView = view?.qrDecoderView ?: return
    qrView.setAutofocusInterval(1000)
    qrView.setOnQRCodeReadListener { text, _ ->
      if (!subject.hasComplete()) {
        subject.onNext(QRCode.camera(text))
        subject.onComplete()
      }
    }

    btnFromAlbum.setOnClickListener { fromAlbum() }
  }

  override fun onResume() {
    super.onResume()
    rxPermissions(ZPermission.CAMERA)
        .subscribe({ granted ->
          if (granted) {
            view?.qrDecoderView?.startCamera()
          } else {
            AlertDialog.Builder(activity).setCancelable(false).setMessage("未授权【相机】权限").show()
          }
        })
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    helper.onActivityResult(requestCode, resultCode, data)
  }

  override fun onPause() {
    super.onPause()
    view?.qrDecoderView?.stopCamera()
  }

  fun observable(): Observable<QRCode> = subject

  private fun onResult(result: QRCode) {
    if (subject.hasComplete().not()) {
      subject.onNext(result)
      subject.onComplete()
    }
  }

  //  识别相册图片二维码
  @Suppress("MemberVisibilityCanPrivate")
  fun fromAlbum() {
    qrcodeFromAlbum().subscribe({ data ->
      onResult(QRCode.album(data))
    }, {
      Toast.makeText(activity, it.message, Toast.LENGTH_LONG).show()
    })
  }
}